from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadTimeSignature,BadSignature
from django.conf import settings

"""
1、创建序列化器：
  参数一 秘钥 一般使用settings-sSERECT_KEY
  参数二 有效期
2、组织数据
3、加密
4、解密

"""
# 1、创建序列化器：
# serializer = Serializer(settings.SECRET_KEY,3600)

#   参数一 秘钥 一般使用settings-sSERECT_KEY
#   参数二 有效期
# 2、组织数据
# data = {"openid":"1345678"}
# 3、加密
# token = serializer.dumps(data)
# 4、解密
# serializer.load(data)

#二进制
# b'eyJpYXQiOjE1NDE3NzQyODgsImV4cCI6MTU0MTc3Nzg4OCwiYWxnIjoiSFM1MTIifQ.
# eyJvcGVuaWQiOiIxMzQ1Njc4In0.
# _QZibF3NE6cqcTiwMC5In41KjnrZN0KYTpISX0cLcA-N8F58oqB35NTpSX4sikXJfzUpEB-8WnN9Cj4mLlL8CQ'
# serializer.loads(token)

def generic_access_token(openid):

    serializer = Serializer(settings.SECRET_KEY, 3600)
    data = {"openid": openid}
    token = serializer.dumps(data)

    return token.decode()

def check_save_user_token(token):
    serializer = Serializer(settings.SECRET_KEY, 3600)
    #解密有可能失败,2种情况
    try:
        result = serializer.loads(token)
        token = result.get('openid')
    except BadSignature:
        return None
    else:
        return token










